﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Odyssey.Controls.Internals;

namespace Odyssey.Controls
{
    /// <summary>
    /// ListBoxItem control used in <see cref="OdcListBox"/>
    /// </summary>
    /// <remarks>
    /// The visual state "Loaded" is set when the ListBoxItem is materialized for the very first time. If the item container does it's first measure, it goes to the state with a transition, oderwise immediately.
    /// </remarks>
    [TemplateVisualState(Name = "Unloaded", GroupName = "VirtualStates")]
    [TemplateVisualState(Name = "Loaded", GroupName = "VirtualStates")]
    public class OdcListBoxItem : ContentControl
    {
        public OdcListBoxItem()
            : base()
        {
            DefaultStyleKey = typeof(OdcListBoxItem);
       //     Loaded += new RoutedEventHandler(OdcListBoxItem_Loaded);
        }

        //void OdcListBoxItem_Loaded(object sender, RoutedEventArgs e)
        //{
        //    Dispatcher.BeginInvoke(delegate
        //    {
        //        VisualStateManager.GoToState(this, VisualStates.LoadedState, true);
        //    });
        //}



        public bool IsHeader
        {
            get
            {
                IGroupItem header = Content as IGroupItem;
                return (header != null && header.IsHeader);
            }
        }




        public object CommandParameter
        {
            get { return (object)GetValue(CommandParameterProperty); }
            set { SetValue(CommandParameterProperty, value); }
        }

        public static readonly DependencyProperty CommandParameterProperty =
            DependencyProperty.Register("CommandParameter", typeof(object), typeof(OdcListBoxItem), new PropertyMetadata(null));



        public ICommand Command
        {
            get { return (ICommand)GetValue(CommandProperty); }
            set { SetValue(CommandProperty, value); }
        }


        public static readonly DependencyProperty CommandProperty =
            DependencyProperty.Register("Command", typeof(ICommand), typeof(OdcListBoxItem), new PropertyMetadata(null));




        /// <summary>
        /// Gets or sets whether the item is selected in the listbox.
        /// </summary>
        public bool IsSelected
        {
            get { return (bool)GetValue(IsSelectedProperty); }
            set { SetValue(IsSelectedProperty, value); }
        }

        public static readonly DependencyProperty IsSelectedProperty =
            DependencyProperty.Register("IsSelected", typeof(bool), typeof(OdcListBoxItem), new PropertyMetadata(false, OnSelectionChanged));

        private static void OnSelectionChanged(DependencyObject o, DependencyPropertyChangedEventArgs args)
        {
            bool isSelected = (bool)args.NewValue;
            (o as OdcListBoxItem).OnSelectionChanged(isSelected);
        }

        protected virtual void OnSelectionChanged(bool isSelected)
        {
            VisualStateManager.GoToState(this, isSelected ? "Selected" : "Unselected", true);
        }


        internal OdcListBox ListBox;

        protected override void OnManipulationCompleted(ManipulationCompletedEventArgs e)
        {
            base.OnManipulationCompleted(e);
            if (!e.Handled)
            {
                if (e.TotalManipulation.Translation == new Point())
                {
                    OnClick();
                    var vel = e.FinalVelocities != null ? e.FinalVelocities.LinearVelocity : new Point();
                    if (vel.X == 0d && vel.Y == 0d)
                    {
                        e.Handled = true;

                        if (IsHeader)
                        {
                            ListBox.IsJumpListOpen = true;
                        }
                        else
                        {
                            var lb = ListBox;
                            if (lb != null)
                            {
                                IsSelected = true;
                                lb.SelectedItem = this.Content;
                            }
                            RaiseCommand();
                            if (lb!=null) lb.ItemClick(this);
                        }

                    }
                }
            }
        }

        private void OnClick()
        {
            var eh = Click;
            if (eh != null) eh(this, EventArgs.Empty);
        }

        public virtual void RaiseCommand()
        {
            var command = Command;
            if (command != null)
            {
                command.Execute(CommandParameter ?? DataContext);
            }
        }


        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            VisualStateManager.GoToState(this, IsSelected ? "Selected" : "Unselected", false);

        }

        public event EventHandler Click;
    }
}
